//
//  UserManager.m
//  MiAiApp
//
//  Created by 徐阳 on 2017/5/22.
//  Copyright © 2017年 徐阳. All rights reserved.
//

#import "UserManager.h"
#define kSTRING1(value) [self valueToString:value]//任意类型转换成字符串

@implementation UserManager


+ (instancetype)sharedUserManager{
    static UserManager * instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

/*
 任何对象转字符串 代替以下方法
 
 @param obj 对象
 @return 字符串
 */
-(NSString *)valueToString:(id)obj{
    
    if ([obj isEqual:nil]) {
        return [NSString string];
    }
    
    if ([obj isEqual:[NSNull null]]) {
        return [NSString string];
    }
    
    if ([obj isKindOfClass:[NSString class]]) {
        return obj;
    }
    
    if ([obj isKindOfClass:[NSNumber class]]) {
        return [NSString stringWithFormat:@"%@", obj];
    }
    
    return [NSString string];
}

-(NSString *)getToken{
    //全局的token
    if (kSTRING([UserManager sharedUserManager].userInfo.token).length > 0) {
        return kSTRING([UserManager sharedUserManager].userInfo.token);
    }
    //缓存的token
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"];
    if (kSTRING(token).length > 0) {
        [UserManager sharedUserManager].userInfo.token = token;
        return token;
    }
    return @"";
}


-(void)saveUserInfo:(NSDictionary *)userInfo{
    if (![UserManager sharedUserManager].userInfo) {
        [UserManager sharedUserManager].userInfo = [[UserInfo alloc] init];
    }
    [UserManager sharedUserManager].userInfo.name = kSTRING(userInfo[@"name"]);
    [UserManager sharedUserManager].userInfo.token = kSTRING(userInfo[@"token"]);
    [UserManager sharedUserManager].userInfo.userId = kSTRING(userInfo[@"user_id"]);
    [[NSUserDefaults standardUserDefaults] setObject:kSTRING(userInfo[@"token"]) forKey:@"userToken"];
    [[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:@"userInfo"];
}

-(void)getUserInfo{
    NSDictionary *userInfo = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    if (userInfo) {
        [UserManager sharedUserManager].userInfo = [UserInfo new];
        [UserManager sharedUserManager].userInfo.index_no = kSTRING(userInfo[@"index_no"]);
        [UserManager sharedUserManager].userInfo.name = kSTRING(userInfo[@"name"]);
        [UserManager sharedUserManager].userInfo.token = kSTRING(userInfo[@"token"]);
        [UserManager sharedUserManager].userInfo.userId = kSTRING(userInfo[@"user_id"]);
    }
}

-(void)removeUserData{
    [UserManager sharedUserManager].userInfo = nil;
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"userToken"];
    [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:@"userInfo"];
}
@end
